package com.wuuxiang.dynamic.mongo.configuration;

import com.wuuxiang.dynamic.mongo.aop.DynamicMongoAnnotationAdvisor;
import com.wuuxiang.dynamic.mongo.aop.DynamicMongoAnnotationInterceptor;
import com.wuuxiang.dynamic.mongo.database.DynamicMongoDatabaseFactory;
import com.wuuxiang.dynamic.mongo.database.DynamicMongoDatabaseFactoryProvider;
import com.wuuxiang.dynamic.mongo.database.DynamicMongoProperty;
import com.wuuxiang.dynamic.mongo.processor.DynamicMongoBeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDatabaseFactory;

@Configuration
@AutoConfigureBefore({MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@EnableConfigurationProperties(DynamicMongoProperty.class)
@ConditionalOnProperty(prefix = DynamicMongoProperty.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class DynamicMongoAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean
	public MongoDatabaseFactory dynamicMongoDatabaseFactory(DynamicMongoProperty dynamicMongoProperty, Environment environment) {
		DynamicMongoDatabaseFactoryProvider dynamicMongoDatabaseFactoryProvider = new DynamicMongoDatabaseFactoryProvider(dynamicMongoProperty, environment);
		return new DynamicMongoDatabaseFactory(dynamicMongoDatabaseFactoryProvider);
	}

	@Bean
	@ConditionalOnMissingBean
	public DynamicMongoAnnotationAdvisor dynamicMongoAnnotationAdvisor() {
		return new DynamicMongoAnnotationAdvisor(new DynamicMongoAnnotationInterceptor());
	}

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnProperty(prefix = DynamicMongoProperty.PREFIX, name = DynamicMongoProperty.REMOVE_UNDER_CLASS, havingValue = "true", matchIfMissing = false)
	public DynamicMongoBeanPostProcessor dynamicMongoBeanPostProcessor() {
		return new DynamicMongoBeanPostProcessor();
	}

}
